package xyz.liuz.edb.heart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.concurrent.ConcurrentHashMap;

public class HeartServer {

    private static ChannelFuture channelFuture;
    public static ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<String, Channel>();
    public static void main(String[] args){
        // 配置服务端的NIO事件循环线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(2);

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 保持长连接
                    .option(ChannelOption.SO_BACKLOG, 500)
                    // 连接个数
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    // 不延迟
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new HeartServerChannelInitializer());
            // 绑定端口，同步等待成功
            channelFuture = b.bind(8889).sync();
            System.out.println("心跳服务启动成功");
            // 等待服务器监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            System.out.println("心跳服务启动失败:"+e);
            throw new RuntimeException();
        } finally {
            // 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }
}
